from Foundation import *
from AppKit import *
import objc

import csv
import sys

import correlate
import readers
import writers

class FlowJo_CorrelationAppDelegate(NSObject):
    inputFile = objc.ivar(u'inputFile')
    format = objc.ivar(u'format')
    correlator = objc.ivar(u'correlator')
    threshold = objc.ivar(u'threshold')

    def applicationDidFinishLaunching_(self, notify):
        self.format = 'smita2'
        self.correlator = 'Pearson'

    def correlations(self):
        rows = csv.reader(open(self.inputFile.path(), 'U'))
        data = readers.__dict__[str(self.format)](rows)
        return correlate.__dict__[str(self.correlator.lower())](data)

    def targetFile(self, func, ext):
        panel = NSSavePanel.savePanel()
        panel.setTitle_('Save as...')
        panel.setRequiredFileType_(ext)
        if panel.runModal() == NSOKButton:
            func(self, panel.filename())
    
    @objc.IBAction
    def output_(self, sender):
        tag = sender.cell().tagForSegment_(sender.selectedSegment())
        self.targetFile([writers.matrix, writers.join, writers.heatmap][tag],
                        ['csv', 'csv', 'pdf'][tag])
